package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.attendance.dto.DepartmentOrUserSimpleDTO;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysDepartmentDTO;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysDepartmentMapper;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysDepartment;
import com.nineclock.system.service.SysDepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysDepartmentServiceImpl implements SysDepartmentService {
    @Autowired
    SysDepartmentMapper departmentMapper;

    /**
     * 查询公司的部门列表
     * @return
     */
    @Override
    public List<SysDepartmentDTO> queryDepartmentList() {
        //获取当前的企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();
        List<SysDepartmentDTO> departmentList = queryChildrenDepartmentList(companyId, 0L);
        return departmentList;
    }

    /**
     * 查询企业ID下的所有顶级部门ID
     * @return
     */
    @Override
    public List<Long> queryDepartmentIds() {
        LambdaQueryWrapper<SysDepartment> departmentQw=new LambdaQueryWrapper<>();

        departmentQw.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());
        departmentQw.eq(SysDepartment::getParentId,0);

        List<SysDepartment> departments = departmentMapper.selectList(departmentQw);

        List<Long> idsList = departments.stream().map(department -> {
            return department.getId();
        }).collect(Collectors.toList());

        return idsList;
    }

    @Autowired
    SysCompanyUserMapper companyUserMapper;
    /**
     * 根据部门ID查询子部门及员工列表
     * @param departmentId
     * @param includeMember
     * @return
     */
    @Override
    public List<DepartmentOrUserSimpleDTO> querySimpleDepartment(Long departmentId, Integer includeMember) {
        if (departmentId == null || includeMember == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        List<DepartmentOrUserSimpleDTO> resultList=new ArrayList<>();

        //查询部门

        LambdaQueryWrapper<SysDepartment> departmentQW=new LambdaQueryWrapper<>();

        departmentQW.eq(SysDepartment::getCompanyId,CurrentUserHolder.get().getCompanyId());
        departmentQW.eq(SysDepartment::getParentId,departmentId);
        List<SysDepartment> departmentList = departmentMapper.selectList(departmentQW);

        if (CollectionUtil.isNotEmpty(departmentList)){
            List<DepartmentOrUserSimpleDTO> departmentSimpleDTOS = departmentList.stream().map(sysDepartment -> {
                DepartmentOrUserSimpleDTO departmentSimpleDTO = new DepartmentOrUserSimpleDTO();
                departmentSimpleDTO.setId(sysDepartment.getId());
                departmentSimpleDTO.setName(sysDepartment.getName());
                departmentSimpleDTO.setType(1);
                return departmentSimpleDTO;
            }).collect(Collectors.toList());
            resultList.addAll(departmentSimpleDTOS);
        }

        //查询员工
        //如果部门为null， 查询员工列表
        //说明包含员工
        if(includeMember == 0){
            LambdaQueryWrapper<SysCompanyUser> companyUserMapperQw = new LambdaQueryWrapper<>();
            companyUserMapperQw.eq(SysCompanyUser::getDepartmentId, departmentId);
            companyUserMapperQw.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
            //查询指定部门的员工列表
            List<SysCompanyUser> companyUserList = companyUserMapper.selectList(companyUserMapperQw);
            if(CollectionUtil.isNotEmpty(companyUserList)){
                //转换为DepartmentOrUserSimpleDTO 类型
                List<DepartmentOrUserSimpleDTO> userSimpleDTOList = companyUserList.stream().map(sysCompanyUser -> {
                    DepartmentOrUserSimpleDTO userSimpleDTO = new DepartmentOrUserSimpleDTO();
                    userSimpleDTO.setId(sysCompanyUser.getId());
                    userSimpleDTO.setName(sysCompanyUser.getUserName());
                    userSimpleDTO.setType(2);

                    return userSimpleDTO;
                }).collect(Collectors.toList());

                //添加到结果集中
                resultList.addAll(userSimpleDTOList);
            }
        }


        return resultList;
    }

    /**
     *  根据员工id获得部门从低到高级别的部门ID集合
     * @param companyUserId
     * @return
     */
    @Override
    public List<Long> queryDepartmentsByUserId(Long companyUserId) {
        List<Long> depIds = new ArrayList<>();

        //1. 查询企业员工记录
        LambdaQueryWrapper<SysCompanyUser> companyUserWrapper = new LambdaQueryWrapper<>();
        companyUserWrapper.eq(SysCompanyUser::getId, companyUserId);
        companyUserWrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());

        SysCompanyUser companyUser = companyUserMapper.selectOne(companyUserWrapper);

        //2. 获取企业的部门ID
        if(companyUser != null){
            Long id = companyUser.getDepartmentId();
            depIds.add(id);

            //3. 获取当前部门的上级部门ID , 如果不存在, 直接跳出
            while (true){
                SysDepartment department = departmentMapper.selectById(id);
                Long parentId = department.getParentId();

                if(parentId != null && parentId != 0){
                    depIds.add(parentId);
                    id = parentId;
                }else{
                    break;
                }
            }
        }
        return depIds;
    }

    /**
     *
     * @param companyId
     * @param parentId
     * @return
     */
    private List<SysDepartmentDTO> queryChildrenDepartmentList(Long companyId , Long parentId) {
        LambdaQueryWrapper<SysDepartment> qw = new LambdaQueryWrapper();
        qw.eq(SysDepartment::getCompanyId, companyId);
        qw.eq(SysDepartment::getParentId, parentId);

        List<SysDepartment> departmentList = departmentMapper.selectList(qw);
        if(CollectionUtil.isEmpty(departmentList)){
            return new ArrayList<SysDepartmentDTO>();
        }

        List<SysDepartmentDTO> departmentDTOList = BeanHelper.copyWithCollection(departmentList, SysDepartmentDTO.class);

        departmentDTOList.forEach(department -> {
            department.setChildren(queryChildrenDepartmentList(companyId, department.getId()));
        });
        return departmentDTOList;
    }
}
